URL Shortener code
import requests
def shorten_url(long_url):
api_url = "http://tinyurl.com/api-create.php"
params = {'url': long_url}
try:
response = requests.get(api_url, params=params)
if response.status_code == 200:
return response.text
else:
return "Error: Could not shorten the URL."
except Exception as e:
return f"Exception occurred: {e}"
def main():
print("--- URL Shortener ---")
long_url = input("Enter the long URL: ").strip()
if not long_url.startswith("http://") and not long_url.startswith("https://"):
long_url = "http://" + long_url # Add scheme if missing
short_url = shorten_url(long_url)
print(f"Shortened URL: {short_url}")
if __name__ == "__main__":
main()
Code output
--- URL Shortener ---
Enter the long URL: https://www.example.com/my-very-long-url
Shortened URL: http://tinyurl.com/xyz123